package com.yinxin.sychornized;

/**
 * @author yinxin
 * @Title:
 * @Package
 * @Description:
 * @date 2022/1/911:20
 */
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();


        new Thread(buyTicket,"t1").start();
        new Thread(buyTicket,"t2").start();
        new Thread(buyTicket,"t3").start();
        /**
         * t2拿到2
         * t3拿到1
         * t2拿到-1  线程不安全,当t2和t1在票为1时候还去创建线程导致多拿票
         * t1拿到0
         */

    }
}

class BuyTicket implements Runnable{

    public static int ticketNum = 100;
    boolean flag = true;
    @Override
    public void run() {
        //买票
        while (flag){
            buy();
        }
    }

    //synchronized 同步方法
    private synchronized void buy(){
        //判断是否有票
        if(ticketNum<=0){
            flag=false;
            return;
        }
        //模拟延时
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNum--);
    }
}
